package com.guiji.text2video.job.service;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.guiji.text2video.common.core.utils.DateUtils;
import com.guiji.text2video.job.domain.Text2videoConfig;
import com.guiji.text2video.job.domain.YoutubeAnalysis;
import com.guiji.text2video.job.domain.YoutubeExeclResult;
import com.guiji.text2video.job.mapper.Text2videoConfigMapper;
import com.guiji.text2video.job.mapper.YoutubeAnalysisMapper;
import com.guiji.text2video.job.mapper.YoutubeExeclResultMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @program: cms-vue-plus
 * @description:
 * @author: gaoX
 * @date 2022/2/10 16:43
 */
@Service
public class YoutubeExeclResultServiceImpl implements IYoutubeExeclResultService {
    @Autowired(required = false)
    private YoutubeExeclResultMapper youtubeExeclResultMapper;
    @Autowired(required = false)
    private Text2videoConfigMapper text2videoConfigMapper;
    @Autowired
    private YoutubeAnalysisMapper youtubeAnalysisMapper;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】ID
     * @return 【请填写功能名称】
     */
    @Override
    public YoutubeExeclResult selectYoutubeExeclResultById(Long id) {
        return youtubeExeclResultMapper.selectYoutubeExeclResultById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param youtubeExeclResult 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<YoutubeExeclResult> selectYoutubeExeclResultList(YoutubeExeclResult youtubeExeclResult) {
        return youtubeExeclResultMapper.selectYoutubeExeclResultList(youtubeExeclResult);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param youtubeExeclResult 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertYoutubeExeclResult(YoutubeExeclResult youtubeExeclResult) {
        youtubeExeclResult.setCreateTime(DateUtils.getNowDate());
        return youtubeExeclResultMapper.insertYoutubeExeclResult(youtubeExeclResult);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param youtubeExeclResult 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateYoutubeExeclResult(YoutubeExeclResult youtubeExeclResult) {
        return youtubeExeclResultMapper.updateYoutubeExeclResult(youtubeExeclResult);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteYoutubeExeclResultByIds(Long[] ids) {
        return youtubeExeclResultMapper.deleteYoutubeExeclResultByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteYoutubeExeclResultById(Long id) {
        return youtubeExeclResultMapper.deleteYoutubeExeclResultById(id);
    }

    @Override
    public void makeExcel() {
        //获取周数
        List<String> weekList = youtubeExeclResultMapper.getWeeks();
        List<Text2videoConfig> text2videoConfigs = text2videoConfigMapper.selectAll();
        int k = 1;
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        String time = sdf1.format(new Date());
        String path = "/data/hdd/secondcreation/excel/"+time+".xls";
        ExcelWriter writer = new ExcelWriter(path, "累计观看量");
        for (int i = 1; i < 7; i++) {
            if (k == 1) {//写第一页数据
                writeData(weekList, text2videoConfigs, "view_count", writer);
            }
            if (k == 2) {//写第二页数据
                writer.setSheet("累计获利");
                writeData(weekList, text2videoConfigs, "income", writer);
            }
            if (k == 3) {//写第三页数据
                writer.setSheet("累计订阅人数");
                writeData(weekList, text2videoConfigs, "subscribe_num", writer);
            }
            if (k == 4) {//写第四页数据
                writer.setSheet("CPM");
                writeData(weekList, text2videoConfigs, "cpm", writer);
            }
            if (k == 5) {//写第五页数据
                writer.setSheet("上传视频数");
                writeData(weekList, text2videoConfigs, "upload_num", writer);
            }
            if (k == 6) {//写第六页数据
                writer.setSheet("观看时长(365)");
                writeData(weekList, text2videoConfigs, "view_time", writer);
            }
            k++;
        }
        //写倒数第二个sheet页
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String timePre = sdf.format(new Date());
        List<YoutubeAnalysis> youtubeAnalysisList = youtubeAnalysisMapper.selectTodayData7(timePre);
        List list = new ArrayList();
        youtubeAnalysisList.forEach(youtubeAnalysis -> {
            LinkedHashMap map = new LinkedHashMap();
            map.put("管理员", youtubeAnalysis.getUpdateBy());
            map.put("账号名称", youtubeAnalysis.getYoutubeAccount());
            map.put("时间", youtubeAnalysis.getCreateTime());
            List<YoutubeExeclResult> dataList = youtubeExeclResultMapper.selectDataIncome("0", timePre);
            int l = 1;
            for (YoutubeExeclResult youtubeExeclResult : dataList) {
                if (youtubeAnalysis.getYoutubeAccount().equals(youtubeExeclResult.getYoutubeAccount())) {
                    map.put("累计获利", youtubeExeclResult.getIndicatorValue());
                    break;
                }
                l++;
                if (l == dataList.size() + 1) {
                    map.put("累计获利", "——");
                }
            }

            map.put("一周获利", youtubeAnalysis.getIncome());
            map.put("一周观看次数", youtubeAnalysis.getViewCount());
            map.put("一周上传数量", youtubeAnalysis.getUploadNum());
            //增加账号天数
            for (Text2videoConfig config : text2videoConfigs) {
                if (youtubeAnalysis.getYoutubeAccount().equals(config.getBackup1())) {
                    long days = DateUtil.between(config.getUpdateTime(), new Date(), DateUnit.DAY);
                    map.put("账号天数", days);
                    break;
                }
            }
            map.put("一周观看时长", youtubeAnalysis.getViewTime());
            list.add(map);
        });
        writer.setSheet("一周统计");
        writer.write(list, true);

        //写最后一个sheet页
        writeLastSheet(writer,text2videoConfigs);
        writer.close();

    }

    private void writeData(List<String> weekList, List<Text2videoConfig> text2videoConfigs, String dimension, ExcelWriter writer) {
        List list = new ArrayList();
        for (Text2videoConfig config : text2videoConfigs) {
            LinkedHashMap map = new LinkedHashMap();
            String admin = config.getUpdateBy();
            String accountName = config.getBackup1();
            map.put("管理员", admin);
            map.put("账号名称", accountName);
            long days = DateUtil.between(config.getUpdateTime(), new Date(), DateUnit.DAY);
            map.put("账号天数", days);
            //循环周数，获取每周数据
            for (int i = 0; i < weekList.size(); i++) {
                String timePre = weekList.get(i);
                List<YoutubeExeclResult> dataList;
                if (dimension.equals("view_time")) {//如果是观看时长则获取365天数据
                    dataList = youtubeExeclResultMapper.select7Data("365", timePre);
                } else {//如果是其他则获取从始至终数据
                    dataList = youtubeExeclResultMapper.select7Data("0", timePre);
                }
                //数据集中查找唯一数据
                int l = 1;
                for (YoutubeExeclResult youtubeExeclResult : dataList) {
                    if (youtubeExeclResult.getYoutubeAccount().equals(accountName) && youtubeExeclResult.getDimension().equals(dimension)) {
                        map.put(timePre, youtubeExeclResult.getIndicatorValue());
                        break;
                    }
                    l++;
                    if (l == dataList.size() + 1) {
                        map.put(timePre, "——");
                    }
                }
            }

            list.add(map);
        }
        writer.write(list, true);
    }
    private void writeLastSheet(ExcelWriter writer,List<Text2videoConfig> text2videoConfigs){
        writer.setSheet("类别统计");
        //获取新闻类别
        Set<String> categorySet = new HashSet();
        text2videoConfigs.forEach(text2videoConfig -> {
            categorySet.add(text2videoConfig.getBackup3());
        });
        Map<String,List> map = new HashMap();
        categorySet.forEach(category ->{
            ArrayList list = new ArrayList();
            text2videoConfigs.forEach(text2videoConfig -> {
                if(category.equals(text2videoConfig.getBackup3())){
                    list.add(text2videoConfig.getBackup1());
                }
            });
            map.put(category,list);
        });
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String timePre = sdf.format(new Date());
        List<YoutubeExeclResult> dataList0 = youtubeExeclResultMapper.selectDataIncome("0", timePre);
        List<YoutubeExeclResult> dataList7 = youtubeExeclResultMapper.selectDataIncome("7", timePre);
        List<Map> resultList = new ArrayList();
        for(String category:map.keySet()){
            LinkedHashMap map1 = new LinkedHashMap();
            map1.put("类别",category);
            List<String> list = map.get(category);
            float totalIncome = 0;
            for(String accountName:list){
                //查找累计收入
                for(YoutubeExeclResult youtubeExeclResult:dataList0){
                    if(youtubeExeclResult.getYoutubeAccount().equals(accountName)){
                        if(ObjectUtil.isNotNull(youtubeExeclResult.getIndicatorValue())&&ObjectUtil.isNotEmpty(youtubeExeclResult.getIndicatorValue())){
                            if(youtubeExeclResult.getIndicatorValue().contains("$")){
                                totalIncome = totalIncome+Float.parseFloat(youtubeExeclResult.getIndicatorValue().replaceAll("\\$",""));
                            }
                        }
                        continue;
                    }
                }
            }
            map1.put("累计获利",totalIncome);
            //查找周收入
            float weekIncome = 0;
            for(String accountName:list){
                //查找累计收入
                for(YoutubeExeclResult youtubeExeclResult:dataList7){
                    if(youtubeExeclResult.getYoutubeAccount().equals(accountName)){
                        if(ObjectUtil.isNotNull(youtubeExeclResult.getIndicatorValue())&&ObjectUtil.isNotEmpty(youtubeExeclResult.getIndicatorValue())){
                            if(youtubeExeclResult.getIndicatorValue().contains("$")){
                                weekIncome = weekIncome+Float.parseFloat(youtubeExeclResult.getIndicatorValue().replaceAll("\\$",""));
                            }
                        }
                        continue;
                    }
                }
            }
            map1.put("一周获利",weekIncome);
            map1.put("账号数量",list.size());
            //结果保留一位小数
            String avg = null;
            try {
                avg = String.format("%.1f", totalIncome / list.size());
            } catch (Exception e) {
                avg = "除法出错";
            }
            map1.put("平均每个账号获利",avg);
            resultList.add(map1);
        }
        //最后在做一个总计
        Map lastMap = new HashMap();
        lastMap.put("类别","总计");
        float totalTotal=0;
        float weeklyTotal=0;
        int countTotal=0;
        for(Map map2:resultList){
            totalTotal = totalTotal+(float)map2.get("累计获利");
            weeklyTotal = weeklyTotal+(float) map2.get("一周获利");
            countTotal = countTotal+(int) map2.get("账号数量");
        }
        lastMap.put("累计获利",totalTotal);
        lastMap.put("一周获利",weeklyTotal);
        lastMap.put("账号数量",countTotal);
        lastMap.put("平均每个账号获利"," ");
        resultList.add(lastMap);

        writer.setSheet("类别统计");
        writer.write(resultList, true);
    }
}
